package rensoft.android.view.grid;

import static rensoft.java.lang.Lang.is;

import rensoft.android.HasActivity;
import rensoft.android.view.ViewBase;
import rensoft.java.event.Event.EventRegistration;
import rensoft.java.event.Task;

public abstract class GridRowBase extends ViewBase implements GridRowView<IGridRequest> {

  private EventRegistration requestForRowLoadRegistration;
  private final HasActivity hasactivity;
  private RowData rowData;

  public GridRowBase(HasActivity hasActivity, int rowLayoutId) {
    super(hasActivity, rowLayoutId);
    hasactivity = hasActivity;
  }

  public void load(RowData rowData) {
    if (is(requestForRowLoadRegistration)) {
      requestForRowLoadRegistration.cancel();
      requestForRowLoadRegistration = null;
    }
    this.rowData = rowData;
    if (rowData.isDone())
      load();
    else {
      setWaiting(true);
      requestForRowLoadRegistration = rowData.eventLoaded().attach(new Task() {
        public void run() {
          onRequestLoaded();
        }
      });
    }
  }

  protected abstract void displayData(RowData data);

  protected void load() {
    setWaiting(false);
    displayData(rowData);
  }

  protected abstract void setWaiting(boolean waiting);

  private void onRequestLoaded() {
    requestForRowLoadRegistration.cancel();
    requestForRowLoadRegistration = null;
    if (hasactivity.isPaused()) return;
    load();
  }
}
